package br.com.modelo;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseEntity<T extends BaseEntity> implements Serializable {

    private static final long serialVersionUID = 1L;
    private Class entityClass;

    public BaseEntity() {
        this.entityClass = this.getEntityClass();
    }

    private Class getEntityClass() {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
            if (actualTypeArguments.length > 0) {
                return (Class) actualTypeArguments[0];
            } else {
                return this.getClass();
            }
        } else {
            return this.getClass();
        }
    }

    public abstract Integer getId();

    public abstract void setId(Integer id);

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        BaseEntity<T> other = (BaseEntity<T>) obj;
        if (this.getId() != null && other.getId() != null) {
            if (this.getId() == other.getId()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return getClass().getName() + "[id=" + getId() + "]";
    }
}
